﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using log4net;
using PersonalWebSite.Models;
using System.Web.Script.Serialization;
using System.Web.Caching;

namespace PersonalWebSite.Common
{
    /// <summary>
    /// Defines the Quotes Manager
    /// </summary>
    public class QuotesManager
    {
        #region Variables
        private static readonly ILog logger = LogManager.GetLogger(typeof(QuotesManager));
        private const string dataFileName = "Quotes.json";
        private const string cacheKeyQuotesFeed = "QuotesFeed";
        protected static readonly TimeSpan quotesCacheDuration = TimeSpan.FromHours(4);
        #endregion

        #region Constructor
        /// <summary>
        /// Inits the class
        /// </summary>
        static QuotesManager()
        {
            log4net.Config.XmlConfigurator.Configure();
        }
        #endregion

        /// <summary>
        /// Fetches the quotes
        /// </summary>
        /// <returns>Quote Items</returns>
        public static QuotesViewModel FetchQuotes()
        {
            return Cache.CacheItem(cacheKeyQuotesFeed, () => FetchQuotesFromDataFile(), new CacheDependency(HttpContext.Current.Server.MapPath("~/Data/" + dataFileName)), null);
        }

        #region Helper Methods
        /// <summary>
        /// Fetches the videos from the data file
        /// </summary>
        /// <returns>Video Items</returns>
        private static QuotesViewModel FetchQuotesFromDataFile()
        {
            try
            {
                QuotesViewModel model = new JavaScriptSerializer().Deserialize<QuotesViewModel>(FileDataManager.LoadFileInfo(dataFileName).Content);
                model.Items = model.Items.OrderByDescending(i => i.Date).ToArray();
                return model;
            }
            catch (Exception ex)
            {
                string message = string.Format("An error occured while trying to fetch the quotes from data file \"{0}\".", dataFileName);
                logger.Error(message, ex);
                throw;
            }
        }
        #endregion
    }
}